<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { onMounted, ref } from 'vue'
import { initialize } from '@/utils/nimService'
import { useSafeAreaInsets } from '@/utils/useSafeAreaInsets'
import { tabbarStore } from './tabbar'
import { tabbarList as _tabBarList, cacheTabbarEnable, selectedTabbarStrategy, TABBAR_MAP } from './tabbarList'

const customTabbarEnable
= selectedTabbarStrategy === TABBAR_MAP.CUSTOM_TABBAR_WITH_CACHE
  || selectedTabbarStrategy === TABBAR_MAP.CUSTOM_TABBAR_WITHOUT_CACHE

/** tabbarList 里面的 path 从 pages.config.ts 得到 */
const tabbarList = _tabBarList.map(item => ({ ...item, path: `/${item.pagePath}` }))

const { safeAreaInsets } = useSafeAreaInsets()

// 计算底部安全区域高度
const safeAreaBottom = ref(0)
const tabbarHeight = ref(100) // 默认高度，单位rpx

// 获取当前页面路径，用于初始化tabbar状态
function getCurrentPagePath() {
  const pages = getCurrentPages()
  if (pages.length > 0) {
    const currentPage = pages[pages.length - 1]
    return `/${currentPage.route}`
  }
  return '/pages/index/index' // 默认首页
}

// 根据当前页面路径初始化tabbar状态
function initTabbarState() {
  const currentPath = getCurrentPagePath()
  // 查找当前路径对应的tabbar索引
  const index = tabbarList.findIndex(item => item.path === currentPath)
  if (index !== -1) {
    tabbarStore.setCurIdx(index)
  }
  else {
    // 如果当前页面不是tabbar页面，则默认选中首页
    tabbarStore.setCurIdx(0)
  }
}

function selectTabBar(index: number) {
  const url = tabbarList[index].path
  tabbarStore.setCurIdx(index)
  if (cacheTabbarEnable) {
    uni.switchTab({ url })
  }
  else {
    uni.navigateTo({ url })
  }
}

async function openWenWenPage() {
  try {
    uni.showLoading({ title: '加载中...' });
    console.log("准备打开问问页面...");

    // 使用initialize方法进行初始化和登录
    const initialized = await initialize();
    
    if (initialized) {
      // 导航到聊天页面
      uni.navigateTo({
        url: '/pages-sub/NEUIKit/page/Chat/index',
        success: () => uni.hideLoading(),
        fail: () => uni.hideLoading(),
      });
    } else {
      uni.hideLoading();
      uni.showToast({
        title: '初始化失败，请重试',
        icon: 'none',
        duration: 2000,
      });
    }
  }
  catch (error) {
    console.error("打开问问页面出错:", error);
    uni.showToast({
      title: '打开问问页面失败，请重试',
      icon: 'none',
      duration: 2000,
    });
  }
}

onMounted(() => {
  // 获取系统信息计算安全区域
  const windowInfo = uni.getWindowInfo()

  if (windowInfo.safeArea) {
    safeAreaBottom.value = windowInfo.windowHeight - windowInfo.safeArea.bottom || 0
  }

  // 初始化tabbar状态
  initTabbarState()
})

// 当页面重新显示时，确保tabbar状态正确
onShow(() => {
  initTabbarState()
})

onLoad(() => {
  // 解决原生 tabBar 未隐藏导致有2个 tabBar 的问题
  const hideRedundantTabbarEnable = selectedTabbarStrategy === TABBAR_MAP.CUSTOM_TABBAR_WITH_CACHE
  hideRedundantTabbarEnable
  && uni.hideTabBar({
    fail(err) {
      console.log('hideTabBar fail: ', err)
    },
    success(res) {
      console.log('hideTabBar success: ', res)
    },
  })

  // 初始化tabbar状态
  initTabbarState()
})
</script>

<template>
  <view v-if="customTabbarEnable" class="custom-tabbar">
    <image
      src="/src/static/tabbar/tabBg.jpg"
      mode="scaleToFill"
      class="relative h-168rpx w-full"
    />
    <view class="tabbar-wrapper absolute left-0 top-0">
      <!-- 前半部分tabbar项 -->
      <view
        v-for="(item, idx) in tabbarList.slice(0, Math.ceil(tabbarList.length / 2))"
        :key="item.path"
        class="tabbar-item"
        @click="selectTabBar(idx)"
      >
        <!-- UI库图标 -->
        <view v-if="item.iconType === 'uiLib'" class="icon-wrapper">
          <view class="tabbar-icon" :class="[`icon-${item.icon}`, idx === tabbarStore.curIdx ? 'active-icon' : '']" />
        </view>
        <!-- UnoCSS图标 -->
        <view v-else-if="item.iconType === 'unocss'" class="icon-wrapper">
          <view class="tabbar-icon" :class="[item.icon, idx === tabbarStore.curIdx ? 'active-icon' : '']" />
        </view>
        <!-- iconfont图标 -->
        <view v-else-if="item.iconType === 'iconfont'" class="icon-wrapper">
          <view class="tabbar-icon" :class="[item.icon, idx === tabbarStore.curIdx ? 'active-icon' : '']" />
        </view>
        <!-- 本地图片 -->
        <view v-else-if="item.iconType === 'local'" class="icon-wrapper">
          <image :src="idx === tabbarStore.curIdx ? item.selectedIconPath : item.iconPath" :lazy-load="true" :class="[idx === tabbarStore.curIdx ? 'active_image' : 'icon-image']" />
        </view>
        <text class="tabbar-text" :class="[idx === tabbarStore.curIdx ? 'active-text' : '']">
          {{ item.text }}
        </text>
      </view>

      <!-- 问问按钮 - 独立于tabbar项，但保持在相同位置 -->
      <view class="tabbar-item wenwen-item" @click="openWenWenPage">
        <view class="special-icon">
          <view class="">
            <image src="https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/guanjia.png" class="h-88rpx w-80rpx" :lazy-load="true" />
          </view>
        </view>
        <text class="tabbar-text">
          问问
        </text>
      </view>

      <!-- 后半部分tabbar项 -->
      <view
        v-for="(item, idx) in tabbarList.slice(Math.ceil(tabbarList.length / 2))"
        :key="item.path"
        class="tabbar-item"
        @click="selectTabBar(idx + Math.ceil(tabbarList.length / 2))"
      >
        <!-- UI库图标 -->
        <view v-if="item.iconType === 'uiLib'" class="icon-wrapper">
          <view class="tabbar-icon" :class="[`icon-${item.icon}`, idx + Math.ceil(tabbarList.length / 2) === tabbarStore.curIdx ? 'active-icon' : '']" />
        </view>
        <!-- UnoCSS图标 -->
        <view v-else-if="item.iconType === 'unocss'" class="icon-wrapper">
          <view class="tabbar-icon" :class="[item.icon, idx + Math.ceil(tabbarList.length / 2) === tabbarStore.curIdx ? 'active-icon' : '']" />
        </view>
        <!-- iconfont图标 -->
        <view v-else-if="item.iconType === 'iconfont'" class="icon-wrapper">
          <view class="tabbar-icon" :class="[item.icon, idx + Math.ceil(tabbarList.length / 2) === tabbarStore.curIdx ? 'active-icon' : '']" />
        </view>
        <!-- 本地图片 -->
        <view v-else-if="item.iconType === 'local'" class="icon-wrapper">
          <image :src="idx + Math.ceil(tabbarList.length / 2) === tabbarStore.curIdx ? item.selectedIconPath : item.iconPath" :lazy-load="true" :class="[idx + Math.ceil(tabbarList.length / 2) === tabbarStore.curIdx ? 'active_image' : 'icon-image']" />
        </view>
        <text class="tabbar-text" :class="[idx + Math.ceil(tabbarList.length / 2) === tabbarStore.curIdx ? 'active-text' : '']">
          {{ item.text }}
        </text>
      </view>
    </view>
  </view>
  <!-- 占位元素，防止内容被底部导航栏遮挡 -->
  <!-- <view
    v-if="customTabbarEnable"
    class="tabbar-placeholder"
    :style="{
      height: `calc(${tabbarHeight}rpx + ${safeAreaBottom}px)`,
    }"
  /> -->
</template>

<style lang="scss">
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  min-height: 100rpx;
  z-index: 999;
}

.tabbar-wrapper {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100%;
  width: 100%;
}

.tabbar-placeholder {
  width: 100%;
}

.tabbar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  // height: 100%;
  position: relative;
}

.wenwen-item {
  // flex: 0 0 auto; /* 不参与flex布局的伸缩 */
  width: 80rpx; /* 设置固定宽度 */
}

.icon-wrapper {
  width: 56rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tabbar-text {
  font-size: 24rpx;
  color: #999999;
  margin-top: 6rpx;
}

.active-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #000;
}

.active-icon {
  color: #000 !important;
}

.special-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -69rpx;
  margin-bottom: 45rpx;
  position: relative;
}

.icon-image {
  width: 48rpx;
  height: 48rpx;
}

.active_image {
  width: 60rpx;
  height: 57rpx;
}

.tabbar-icon {
  font-family: 'wd-icons' !important;
  font-style: normal;
  font-weight: normal;
  font-variant: normal;
  text-transform: none;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-size: 40rpx;
  color: #999999;
}

/* 安全区域适配 */
.safe-area-inset-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
